"""
--------------------------------------------------------
@File             : test5.py
@Creat Time       : 2021-01-30
@Author           : wangzp
@Site             :
@Software         : PyCharm
@file Conent      :
--------------------------------------------------------
@Revise history   :
@Version          : V12
@Amendant records :
     1)wangzp  2021/01/30
"""




import socket

import time
import threading



socketC = ""               # 创建客户端的socket
socketS = ""               # 创建服务端的socket
inString = ""              # 接收的数据
outString = "要发送的数据B"  # 要发送的数据
client = ("","")          # 服务器接收的socket
connectState = 0
socketSR = "" # 用于收发的socket

# 发起客户端的任务
def CommuChannelClientTaskFunction():
    global socketC
    global connectState
    global socketSR
    while True:
        while connectState == 0:
            try:
                socketC = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                print("尝试建立连接")
                socketC.connect(("127.0.0.1",8888))
                connectState = 1
                print("连接成功")
                socketSR = socketC
                break
            except Exception as e:
                print("出现例外！"+str(e))
                connectState = 0
                continue

# 发起服务端的任务
def CommuChannelServerTaskFunction():
    global socketS
    global client # 客户端返回的socket
    global socketSR
    global connectState
    socketS = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socketS.bind(("127.0.0.1",8123))
    socketS.listen(10)
    while True:
        while connectState == 0:
           try:
               print("等待连接")
               client =  socketS.accept()
               print("连接成功")
               connectState = 1
               socketSR = client[0]
               break
           except Exception as e:
               print("未连接"+str(e))
               connectState = 0
               client[0].close()
               continue
               pass

# 用于接收消息
def MsgResv():
    global  socketSR
    global inString
    global connectState
    while True:
        if socketSR =="":
            continue
        time.sleep(2)
        try:
            inString = socketSR.recv(1024)
            print("接收到的数据为:"+inString.decode("utf-8"))
        except:
            print("未接收到")
            connectState = 0
            socketSR == ""
            pass
# 用于发送信息
def MsgSend():
    global socketSR
    global  outString
    global connectState
    while True:
        if socketSR == "":
            continue
        time.sleep(2)
        try:
            socketSR.send(outString.encode('utf-8'))
            print("发送了一条数据：{0}".format(outString))
        except Exception as e:
            print("发送失败" + str(e))
            connectState = 0
            socketSR == ""
            pass



if __name__ == '__main__':
     i = int(input("请选择客户端（0）/服务端（1）："))
     if(i == 0):

         print("选择了客户端")

         CommuChannelClient = threading.Thread(target=CommuChannelClientTaskFunction)
         CommuChannelClient.start()

         th_send = threading.Thread(target=MsgSend)
         th_send.start()
         th_accept = threading.Thread(target=MsgResv)
         th_accept.start()
     else:

         print("选择了服务端")
         CommuChannelServerTask = threading.Thread(target=CommuChannelServerTaskFunction)
         CommuChannelServerTask.start()

         th_send = threading.Thread(target=MsgSend)
         th_send.start()
         th_accept = threading.Thread(target=MsgResv)
         th_accept.start()
